using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Data;

namespace Evolution.Engine.Items
{
    public class Item
    {
        private string _Script;
        private string _Name;
        private string _ImageFile;
        private int _Count;
        private ItemCost _Cost;

        public ItemCost Cost { get { return _Cost; } set { _Cost = value; } }
        public int Count { get { return _Count; } set { _Count = value; } }
        public string ImageFile { get { return _ImageFile; } set { _ImageFile = value; } }
        public string Name { get { return _Name; } set { _Name = value; } }
        public string Script { get { return _Script; } set { _Script = value; } }

        public Item(string Name, string Script, string ImageFile, int Cost)
        {
            _Name = Name;
            _Script = Script;
            _ImageFile = ImageFile;
            _Cost = new ItemCost(Cost);
        }

        public static ItemCollection GetItems()
        {
            ItemCollection retVal = new ItemCollection();
            DataSet items = new DataSet();
            items.ReadXml("Content/Items/Items.xml");

            foreach (DataRow item in items.Tables[0].Rows)
            {
                retVal.Add(new Item(
                        item["Name"].ToString(),
                        item["Script"].ToString(),
                        item["ImageFile"].ToString(),
                        Convert.ToInt32(item["Cost"].ToString())
                    )
                );
            }

            return retVal;
        }
    }

    public class ItemCollection : Collection<Item>
    {
        public new void Add(Item item)
        {
            if (item.Count == 0) item.Count = 1;
            Item index = ItemExist(item);
            if (index != null)
            {
                index.Count += item.Count;
                item = null;
                return;
            }
            base.Items.Add(item);
        }

        private Item ItemExist(Item item)
        {
            foreach (Item iItem in Items)
            {
                if (iItem.Name == item.Name)
                    return iItem;
            }

            return null;
        }
    }
}
